import React from 'react'
import { Route, Switch } from 'react-router-dom'
import routes from './routes'

/**
 * 渲染顶级页面
 * @returns 一组route
 */
export default function RootRouter() {
    return (
        <>
            {getRoutes(routes, '')}
        </>
    )
}

/**
 * 得到一组Route组件
 * @param {Array} routes 路由数组
 * @param {String} basePath 基础路径，默认为空字符串
 * @returns Route数组
 */
function getRoutes(routes, basePath) {
    const rts = routes.map((route, i) => {
        const { children, name, path, component: Component, ...rest } = route
        const newPath = `${basePath}${path}`.replace(/\/+/g, '/') // 去除多余的'/'
        return <Route
            key={i}
            {...rest}
            path={newPath}
            render={props => {
                return <Component {...props}>
                    {children && getRoutes(children, newPath)}
                </Component>
            }}
        />
    })
    return <Switch>
        {rts}
    </Switch>
}